﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.IO;
using HU8.Web.FileExplorer.FileExplorer.Config;
using System.Configuration;
using XMK.Tadong.Biz;
using XMK.Tadong.Model;



namespace HU8.Web.FileExplorer.FileExplorer
{
    public partial class Default : FileExplorerPage
    {
        private string rootPath;

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                
                string user_id = Request.Cookies["_userId_"].Value; // Request.QueryString["userId"];//  Request.Form["userId"]; // LoginUserBiz.LoginUserID(); // Request.QueryString["user_id"] 

                    if (string.IsNullOrEmpty(user_id))
                    {
                        Response.Write(lang.Get("SPACE_Login has expired, please re login"));
                        Response.End();
                        return;
                    }

                    if (String.IsNullOrEmpty(user_id))
                    {
                        Response.Write("Name Is NULL");
                        Response.End();
                        return;
                    }
                    Session.Timeout = 60;//分钟
                    Session["user_id"] = user_id;
                    Context.Response.Cookies["user_id"].Value = user_id;
                    InitHiddenType_Name_IsAdmin(user_id);//初始化下拉列表
                    initDirAndInfo(user_id, "Individual", true);//初始化全局session 和存放路径
                    InitListDiv("individual", true, user_id,"isAdmin");
                    this.hiddenType_Name_IsAdmin.Value = "individual|" + user_id;
                    Context.Response.Cookies["team_id"].Value = "";
                    this.hiddenSpace_Name.Value = lang.Get("SPACE_Personal_space");
                    //插入日志
                    string IP = Request.ServerVariables["REMOTE_ADDR"].Equals("::1") ? "127.0.0.1" : Request.ServerVariables["REMOTE_ADDR"];
                    XMK.Tadong.Model.Cond.Base_PageLog pageLogModel = new XMK.Tadong.Model.Cond.Base_PageLog();
                    pageLogModel.pageName = "Zone";
                    pageLogModel.ip = IP;
                    XMKLogBiz.WriteLogScanPage(pageLogModel);
                }
            //只有当用户选择 其他空间时才会触发postback事件
            if (IsPostBack)
            {
                
                string[] value = this.hiddenType_Name_IsAdmin.Value.Split('|');// eg  group|individual|project(类型)-课题组1(标示名)-isAdmin(标示是否是管理员，如果不是，则没有次字符串)
                string strType = value[0].Trim(); // group|individual|project
                string strName = value[1].Trim();// 空间名称
                string strIsAdmin = value[2].Trim();//IsAdmin
                this.hiddenSpace_Name.Value = value[3].Trim();

                bool isAdmin = !string.IsNullOrEmpty(strIsAdmin);

                if (Session["user_id"] == null)
                {
                    Session["user_id"] = Context.Request.Cookies["user_id"].Value;
                }

                string user_id = Session["user_id"].ToString();

                if (strType == "individual")
                {
                    this.hidden_identity.Value = "";
                    initDirAndInfo(user_id, "Individual", true);
                }
                else if (strType == "group")
                {
                    Context.Response.Cookies["team_id"].Value = strName;//team id

                    if (isAdmin)
                    {
                        initDirAndInfo(strName, "Group", true);
                        this.hidden_identity.Value = "";
                    }
                    else
                    {
                        initDirAndInfo(strName, "Group", false);
                        this.hidden_identity.Value = "visit";
                    }
                }
                else if (strType == "project")
                {
                   
                    if (isAdmin)
                    {
                        initDirAndInfo(strName, "Project", true);
                        TB_Tree_ObjectBiz objBiz = new TB_Tree_ObjectBiz();
                        string mainPath = config.FilesPath; //ConfigurationManager.AppSettings.Get("DiskPath")+"Project";
                       // objBiz.CheckFileSystem(mainPath);
                        this.hidden_identity.Value = "";
                    }
                    else
                    {
                        initDirAndInfo(strName, "Project", false);
                        this.hidden_identity.Value = "visit";
                    }
                }
                InitListDiv(strType, isAdmin, strName, strIsAdmin);
               


            }
            
            // baseUrl 中存放的是jquery FileTree 的初始目录
            this.baseUrl.Value = config.FilesPath;//Server.MapPath(config.BasePath);// ("~/Excels/");
            //this.baseUrl.Value = config.BasePath;
            this.Title = lang.Get("SPACE_ExploraEExploration Project Databasetion");//"塔东项目库"; //load title
           // ltrLanguage.Text = "";// config.LanguageSelectBox();

            rootPath = "~/"; // config.BasePath;
            //set javascript paths
            hfCurrentPath.Value = rootPath;
            litScript.Text = string.Format("var base_url = \"{0}\";", VirtualPathUtility.ToAbsolute(rootPath));
            litScript.Text += string.Format("var file_base_url = \"{0}\";", VirtualPathUtility.ToAbsolute(config.BasePath));
            litScript.Text += string.Format("var fe_url = \"{0}\";", VirtualPathUtility.ToAbsolute(config.FileExplorerPath));
        }
        private void InitListDiv(string strType, bool isAdmin, string Name, string strIsAdmin)
        {
            string str = "";
            
       

            if (strType == "individual")
            {
                str = @"<div class='submenu mysubmit' style=' width:95%' title= '" + lang.Get("SPACE_I_submit") + "' content='" + Name + @"'>" + lang.Get("SPACE_I_submit") + "</div>"+
                       "<div class='submenu mysubmitback' style=' width:95%' title= '" + lang.Get("SPACE_I_back") + "' content='" + Name + @"'>" + lang.Get("SPACE_I_back") + "</div>" +
                       "<div class='submenu myshare' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_I_shared") + "' >" + lang.Get("SPACE_I_shared") + "</div>" +
                       "<div class='submenu Recycle' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_Recycle") + "' >" + lang.Get("SPACE_Recycle") + "</div>";

            }
            else if (strType == "group")
            {

                if (isAdmin)
                {
                    if (strIsAdmin == "manage")
                    {
                        str = @"<div class='submenu preverify_group' style=' width:95%' title='" + lang.Get("SPACE_Pending_review") + "'  content='" + Name + @"' >" + lang.Get("SPACE_Pending_review") + "</div> " +
                           "<div class='submenu afterverify_group' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_Have_audited") + "' >" + lang.Get("SPACE_Have_audited") + "</div>" +
                           "<div class='submenu checkshare_group' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_View_sharing") + "' > " + lang.Get("SPACE_View_sharing") + "</div>" +
                           "<div class='submenu TeamRecycle' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_Recycle") + "' >" + lang.Get("SPACE_Recycle") + "</div>";
                    }
                    else
                    {
                        str = @"<div class='submenu submit_project' style=' width:95%' title='" + lang.Get("SPACE_I_submit") + "'  content='" + Name + @"'>" + lang.Get("SPACE_I_submit") + "</div> " +
                           "<div class='submenu back_project' style=' width:95%' title='" + lang.Get("SPACE_I_back") + "'  content='" + Name + @"'>" + lang.Get("SPACE_I_back") + "</div> " +
                           "<div class='submenu preverify_group' style=' width:95%' title='" + lang.Get("SPACE_Pending_review") + "'  content='" + Name + @"' >" + lang.Get("SPACE_Pending_review") + "</div> " +
                           "<div class='submenu afterverify_group' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_Have_audited") + "' >" + lang.Get("SPACE_Have_audited") + "</div>" +
                           "<div class='submenu checkshare_group' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_View_sharing") + "' > " + lang.Get("SPACE_View_sharing") + "</div>" +
                           "<div class='submenu TeamRecycle' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_Recycle") + "' >" + lang.Get("SPACE_Recycle") + "</div>";
                    }
                }
                else
                {
                    str = @"<div class='submenu afterverify_group' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_View_SubmitFile") + "'>" + lang.Get("SPACE_View_SubmitFile") + "</div>"+
                            "<div class='submenu checkshare_group' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_View_sharing") + "'>" + lang.Get("SPACE_View_sharing") + "</div>";
                }
            }
            else if (strType == "project")
            {

                if (isAdmin)
                {
                    str = @"<div class='submenu preverify_project' style=' width:95%' title='" + lang.Get("SPACE_Pending_review") + "'  content='" + Name + @"'>" + lang.Get("SPACE_Pending_review") + "</div>"+ 
                            "<div class='submenu afterverify_project' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_Have_audited") + "'>" + lang.Get("SPACE_Have_audited") + "</div>"+
                           "<div class='submenu checkshare_project' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_View_sharing") + "'>" + lang.Get("SPACE_View_sharing") + "</div>"+
                           "<div class='submenu ProjectRecycle' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_Recycle") + "' >" + lang.Get("SPACE_Recycle") + "</div>";
                }
                else
                {
                    str = @"<div class='submenu afterverify_project' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_View_SubmitFile") + "'>" + lang.Get("SPACE_View_SubmitFile") + "</div>"+
                           "<div class='submenu checkshare_project' content='" + Name + @"' style=' width:95%' title='" + lang.Get("SPACE_View_sharing") + "' >" + lang.Get("SPACE_View_sharing") + "</div>";
                }
            }


            this.listDiv.Text = str;

        }

        /// <summary>
        /// 根据用户id初始化空间下拉列表
        /// </summary>
        /// <param name="userId"></param>
        private void InitHiddenType_Name_IsAdmin(string userId)
        {
            Tb_Team_UserBiz teamBiz = new Tb_Team_UserBiz();
            List<Base_UserSpaceInfo> spaces = teamBiz.GetSpaceListByUserId(userId);

            string strFormat = "<div style='width:95%' class='submenu space' content='{0}' >{1}</div>";
            this.LiteralSpace.Text = "";

            this.LiteralSpace.Text += string.Format(strFormat, "individual" + "|" + userId + "|" + "IsAdmin", lang.Get("SPACE_Personal_space"));
            string userAccount = Request.Cookies["_userAccount_"].Value;
  
            if (String.IsNullOrEmpty(userAccount))
            {
                Response.Write(lang.Get("SPACE_Login has expired, please re login"));// ("登录已经过期，请重新登录");
                Response.End();
                return;
            }

            //if (userAccount == "xmksystem")
            //{
            //    this.LiteralSpace.Text += string.Format(strFormat, "project" + "|" + userId + "|" + "IsAdmin", "项目库空间");
            //}
            //else
            //{
            //    this.LiteralSpace.Text += string.Format(strFormat, "project" + "|" + userId + "|", "项目库空间");
            //}

            for (int i = 0; i < spaces.Count; i++)
            {
                if (!spaces[i].IsOpen)
                {
                    continue;
                }
                string strIsAdmin = "";
                if (spaces[i].IsAdmin)
                {
                    strIsAdmin = "IsAdmin";
                    if (spaces[i].SpaceId == "16")
                    {
                        strIsAdmin = "manage";
                    }
                }
                else if (spaces[i].IsDataAdmin)
                {
                    strIsAdmin = "manage";
                }
                //if (spaces[i].SpaceName == lang.Get("xxx"))
                
                if (spaces[i].SpaceId == "17")
                {
                    if (spaces[i].IsAdmin || spaces[i].IsDataAdmin)
                    {
                        this.LiteralSpace.Text += string.Format(strFormat, "project" + "|" + userId + "|" + "IsAdmin", lang.Get("SPACE_Project_space"));
                    }
                   
                    else
                    {
                        this.LiteralSpace.Text += string.Format(strFormat, "project" + "|" + userId + "|", lang.Get("SPACE_Project_space"));
                    }
                }
                else
                {
                    LiteralSpace.Text += string.Format(strFormat, "group" + "|" + spaces[i].SpaceId + "|" + strIsAdmin, spaces[i].SpaceName);
                }
            }

        }

        /// <summary>
        /// 根据用户ID，获取用户的角色等信息,并初始化cookie和session
        /// </summary>
        /// <param name="user_id"></param>
        private void initDirAndInfo(string folderName, string parentFolderName, bool isAdmin)
        {
            string dir = config.MainPath + parentFolderName + "/";
            System.IO.DirectoryInfo dir_info = new System.IO.DirectoryInfo(dir);
            if (!dir_info.Exists)
            {
                //dir_info.Create();
            }
            if (parentFolderName != "Project")
            {
                dir += folderName + "/";
            }
            dir_info = new System.IO.DirectoryInfo(dir);
            if (!dir_info.Exists)
            {
                //dir_info.Create();
            }

            if (parentFolderName == "Group" || parentFolderName == "Project")
            {
                string dirYS = dir +lang.Get("SPACE_Pending_review") + "/";//"待审核" + "/";
                dir_info = new System.IO.DirectoryInfo(dirYS);
                if (!dir_info.Exists)
                {
                    //dir_info.Create();
                }
            }
            Context.Response.Cookies["sub_path"].Value = parentFolderName + "/" + folderName + "/" ;
            Context.Session["sub_path"] = parentFolderName + "/" + folderName + "/" ;
        }

    }
}